package com.zbkj.client.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * 阿里云短信服务工具类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@Component
public class SmsUtil {

	@Value("${aliyun.sms.access-key-id:}")
	private String accessKeyIdDash;

	@Value("${aliyun.sms.access-key-secret:}")
	private String accessKeySecretDash;

	@Value("${aliyun.sms.sign-name:}")
	private String signNameDash;

	@Value("${aliyun.sms.template-code:}")
	private String templateCodeDash;

	@Value("${aliyun.sms.endpoint:dysmsapi.aliyuncs.com}")
	private String endpoint;

	// 短信服务固定区域为杭州
//	@Value("${aliyun.sms.region-id:cn-hangzhou}")
//	private String regionId;

	private Client client;

	/**
	 * 初始化阿里云短信客户端
	 */
	@PostConstruct
	public void initClient() {
		try {
			String accessKeyId = accessKeyIdDash;
			String accessKeySecret = accessKeySecretDash;
			String signName = signNameDash;
			String templateCode = templateCodeDash;

			if (accessKeyId == null || accessKeySecret == null) {
				log.warn("阿里云短信服务配置不完整，请检查 accessKeyId/accessKeySecret 配置");
				return;
			}

			Config config = new Config()
					.setAccessKeyId(accessKeyId)
					.setAccessKeySecret(accessKeySecret)
					.setEndpoint(endpoint);
//					.setRegionId(regionId);

			client = new Client(config);
			log.info("阿里云短信客户端初始化成功, endpoint={},  signName={}, templateCode={}", endpoint,
					signName != null ? signName : "未配置", templateCode != null ? templateCode : "未配置");
		} catch (Exception e) {
			log.error("阿里云短信服务客户端初始化失败", e);
		}
	}

	/**
	 * 发送短信验证码
	 *
	 * @param phone 手机号
	 * @param code  验证码
	 * @return 发送结果
	 */
	public boolean sendCode(String phone, String code) {
		return sendCode(phone, code, null);
	}

	/**
	 * 发送短信验证码（带自定义模板参数）
	 *
	 * @param phone      手机号
	 * @param code       验证码
	 * @param templateParams 自定义模板参数
	 * @return 发送结果
	 */
	public boolean sendCode(String phone, String code, Map<String, String> templateParams) {
		if (client == null) {
			log.error("阿里云短信服务客户端未初始化");
			return false;
		}

		if (phone == null || phone.trim().isEmpty()) {
			log.error("手机号不能为空");
			return false;
		}

		if (code == null || code.trim().isEmpty()) {
			log.error("验证码不能为空");
			return false;
		}

		try {
			// 使用中划线配置项
			String signName = signNameDash;
			String templateCode = templateCodeDash;

			// 构建模板参数
			String templateParam = buildTemplateParam(code, templateParams);

			// 创建发送短信请求
			SendSmsRequest sendSmsRequest = new SendSmsRequest()
					.setPhoneNumbers(phone)
					.setSignName(signName)
					.setTemplateCode(templateCode)
					.setTemplateParam(templateParam);

			// 发送短信
			RuntimeOptions runtime = new RuntimeOptions();
			SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);

			// 处理响应结果
			if (response != null && response.getBody() != null) {
				String codeResult = response.getBody().getCode();
				String message = response.getBody().getMessage();
				String requestId = response.getBody().getRequestId();

				if ("OK".equals(codeResult)) {
					log.info("短信发送成功 - 手机号: {}, 请求ID: {}", phone, requestId);
					return true;
				} else {
					log.error("短信发送失败 - 手机号: {}, 错误码: {}, 错误信息: {}, 请求ID: {}",
							phone, codeResult, message, requestId);
					return false;
				}
			} else {
				log.error("短信发送失败 - 手机号: {}, 响应为空", phone);
				return false;
			}

		} catch (Exception e) {
			log.error("短信发送异常 - 手机号: {}, 错误信息: {}", phone, e.getMessage(), e);
			return false;
		}
	}

	/**
	 * 构建模板参数
	 *
	 * @param code           验证码
	 * @param templateParams 自定义模板参数
	 * @return JSON格式的模板参数
	 */
	private String buildTemplateParam(String code, Map<String, String> templateParams) {
		StringBuilder paramBuilder = new StringBuilder();
		paramBuilder.append("{\"code\":\"").append(code).append("\"");

		// 添加自定义模板参数
		if (templateParams != null && !templateParams.isEmpty()) {
			for (Map.Entry<String, String> entry : templateParams.entrySet()) {
				paramBuilder.append(",\"").append(entry.getKey()).append("\":\"")
						.append(entry.getValue()).append("\"");
			}
		}

		paramBuilder.append("}");
		return paramBuilder.toString();
	}

	/**
	 * 检查短信服务是否可用
	 *
	 * @return 是否可用
	 */
	public boolean isAvailable() {
		String accessKeyId = accessKeyIdDash;
		String accessKeySecret = accessKeySecretDash;
		String signName = signNameDash;
		String templateCode = templateCodeDash;
		return client != null &&
				accessKeyId != null && !accessKeyId.trim().isEmpty() &&
				accessKeySecret != null && !accessKeySecret.trim().isEmpty() &&
				signName != null && !signName.trim().isEmpty() &&
				templateCode != null && !templateCode.trim().isEmpty();
	}

	/**
	 * 获取配置信息（用于调试）
	 *
	 * @return 配置信息
	 */
	public String getConfigInfo() {
		String accessKeyId = accessKeyIdDash;
		String signName = signNameDash;
		String templateCode = templateCodeDash;
		return String.format("阿里云短信配置 - AccessKeyId: %s, SignName: %s, TemplateCode: %s, Endpoint: %s, RegionId: %s",
				accessKeyId != null ? accessKeyId.substring(0, Math.min(8, accessKeyId.length())) + "***" : "未配置",
				signName != null ? signName : "未配置",
				templateCode != null ? templateCode : "未配置",
				endpoint);
	}
} 